<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: ResourceController.php 465 2012-02-12 05:33:23Z beimuaihui $
 */



class System_ResourceController extends Baogg_Controller_Action {

	function init() {
		Zend_Loader::loadClass ( 'Resource' );
		$this->resource = new Resource ( );

	}

	/**
	 * The default action
	 */
	public function listAction() {
		global $LANG;
		
		$params=$this->getRequest()->getParams();
		$form_url=$params;
		
		Zend_Loader::loadClass("Baogg_View_Extgrid");
		
		$cm=array();
		
		$cm['resource_name']=array("sortable"=>true);
		$cm['resource_code']=array("sortable"=>true);
		//$cm['resource_pid']=array("hidden"=>true);
		//$cm['resource_p_name']=array("sortable"=>false);
		$cm['model_id']=array("hidden"=>true);
		$cm['model_name']=array("sortable"=>false);
		$cm['filter']=array("sortable"=>false);			
		$cm['sorting']=array("sortable"=>false);		
		$cm['state']=array("sortable"=>true,"width"=>30);
		$cm['ordering']=array("sortable"=>true);
		$cm['resource_id']=array("hidden"=>false,"cmType"=>Baogg_View_Extgrid::CMTYPE_PK) ;
		//$cm['action']=array("sortable"=>true);
		//$cm['sub_table']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_SUBTABLE) ; //Baogg_View_Extgrid::;
		
		$form_url['action']="data";
		$grid=new Baogg_View_Extgrid($form_url, $cm);
		$grid->setSelectionModel(true);
		$grid->setRowNumberer(true);
		$grid->addExistButtons(array('add','remove','query'),array('edit','delete','resource_op','op_in_resource','role_resource'));
	//$grid->registerButton("resource_fields","window.location.href='".BAOGG_BASE_URL."system/resourceop/list/';");
		
		$this->view->form_url=BAOGG_BASE_URL."system/resource/save";
		$this->view->LANG=Zend_Json::encode($LANG);
		$this->view->grid = $grid->render();
		
		$form_url['action']='add';
		$form=new Baogg_View_Extform(array("url"=>$form_url,"height"=>300,"width"=>600));
	
		$form->addItem(0,array('name'=>'resource_name'));
		
		/* $store_resource=$this->resource->getComboTree(array('state'=>1),null,null,array('resource_id','resource_name','resource_pid'));
		array_unshift($store_resource,array('0',BAOGG_LANGUAGE::get('please_select')));
		 */
		$Model=new Model();
		$store_model=$Model->getCombo(array('state'=>1),null,null,array('model_id','model_name'));
		
		//$form->addItem(0,array('name'=>'resource_pid','xtype'=>'combo','store'=>$store_resource));
		$form->addItem(0,array('name'=>'model_id','xtype'=>'combo','store'=>$store_model));		
		$form->addItem(1,array('name'=>'resource_code'));
		$form->addItem(1,array('name'=>'filter'));
		$form->addItem(1,array('name'=>'sorting'));
		$form->addItem(2,array('name'=>'state','xtype'=>'radiogroup','source'=>BAOGG_LANGUAGE::array2store("arr_state")));
		$form->addItem(2,array('name'=>'ordering'));		
		$form->addItem(2,array('name'=>'resource_id',"xtype"=>"hidden","hideLabel"=>true));		
		$form->addExistButtons(array('-','save_grid','save_new','save','-','search','-','cancel'));//,'config','config'
		//$form->addExistButtons(array('search','add','edit','delete','remove','resource_op','role_resource','reset'),array('edit','delete','resource_op','role_resource'));
		
		$this->view->form=$form;
		//echo '<pre>';var_dump($LANG);exit;


	}

	/**
	 * The data action
	 */
	function dataAction() {
		global $LANG;
	    $post=$this->_request->getPost ();
	    $where=array();$order=array();$limit=array();
	   foreach((array)$post as $k=>$v){
	       if($k=="start" || $k=="limit"){
	           $limit[$k]=$v;
	       }else if($k=="sort" || $k=="dir"){	       		
	           $order[$k]=$v;
	       }else{
	           if($k=="resource_id"  ){
	               if($v && is_numeric($v)){
	                   $v=(int)$v;
	                   $where[$k]=$v;
	               }
	           }else{
	               $v='%'.$v.'%';
	               $where[$k]=$v;
	           }
	           
	       }
	   }
	   if(!count($order)){
	   		$order=array("sort"=>"ordering","dir"=>"asc");
	   }
	   // echo __FILE__.'<pre>';print_r($order);var_dump($order); exit;
        $rs=$this->resource->getList($where,$order,$limit,array('resource_id','resource_name','resource_pid','*'));
        $cnt=$this->resource->getList($where,null,null,"count(*) as cnt");
        $Model=new Model();
        foreach((array)$rs as $k=>$v){
        	$rs[$k]['model_name']='';
        	$rs_model=$Model->getOne((int)$v['model_id']);        	
        	if($rs_model){
        		$rs[$k]['model_name']=$rs_model[0]['model_name'];
        	}
        	
        }
        
		$this->view->grid = Zend_Json::encode(array("count"=>$cnt[0]['cnt'],"data"=>$rs));
	}

	
	/**
	 * The add action
	 */
	function addAction(){
		$this->saveAction();		
	}
	
	/**
	 * The edit action
	 */
	function editAction() {
		$this->saveAction();
	}

	/**
	 * The delete action
	 */
	function deleteAction() {
        
	    $ret=array("success"=>false,"msg"=>"delete_fail");
	    $id = Baogg_Controller_Action::_getParam ( 'ids' );
		 
		   
		
		if ($this->resource->_delete ( $id )){
			$ret['success'] = true;
			$ret["msg"]="delete_ok";
		}
		
		echo Baogg_Language::outputResult($ret);
		 $this->_helper->viewRenderer->setNoRender ();
	}
	
	function removeAction(){
		$this->deleteAction();
	}

	/**
	 * The save action
	 */
	function saveAction() {
		//global $LANG;
		
	    $ret=array("success"=>false,"msg"=>"save_fail");
	    
	    //check form
		if (!$this->_request->isPost ())
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;
		}
		
		$formData = $this->_request->getPost ();

		if(!$formData)
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;     
		}
			
		$arr=$this->resource->filterForm($formData);
        $action=$this->getRequest()->getParam('action');
		$rs = $this->resource->getSame($arr);
		
		
		
		if($action=='edit'){
			$flag=(!$rs) || (count($rs)==1 && $rs[0]==$arr['resource_id']);
			if(!$flag){		
				$ret['msg'] = "exist_same_record";
				echo Baogg_Language::outputResult($ret);
	            exit;
			}
							
		    $this->resource->_update($arr,$arr["resource_id"]);
		    
		    
		    $ret['success'] = true;				
			$ret['msg'] = "save_ok";		
		}else{	
			if(is_array($rs) && count($rs)>0){		
				$ret['msg'] = "exist_same_record";
				echo Baogg_Language::outputResult($ret);
	            exit;
			}
				
			$resource_id=$this->resource->_insert($arr);
			
			$ret['success'] = $resource_id?true:false;
			$ret['msg'] = "add_ok";
		}
				
		echo Baogg_Language::outputResult($ret);
		
		$this->_helper->viewRenderer->setNoRender ();
		
		
	}
	
	function roleAction()
	{
		global $LANG;
		
		$resource_id=(int)$this->getRequest()->getParam('resource_id');
		$item=$this->resource->getOne($resource_id);
		
		//must show role,resource select first
		if(!$this->getRequest()->isPost() || !$this->getRequest()->getParam('role_id') || !$this->getRequest()->getParam('resource_id')){
			
			Zend_Loader::loadClass('Role');
			$role=new Role();
			$this->view->roles=$role->getList(array("state"=>1));
			$this->view->role_id=0;
			
			$this->view->resources=$item;
			$this->view->resource_id=$resource_id;			
			$this->view->gridShow=false;
			$this->view->LANG=$LANG;
			
		}else if(!$this->getRequest()->getParam('resource_row_id')){			
			//show resource_row_id list		
			$resouces=$this->resource->getResource(@$item[0]);
			$this->view->resources=$resouces;		
			
			
			Zend_Loader::loadClass("ResourceOp");
			$op=new ResourceOp();
			$rs_op=$op->getList(array("resource_id"=>$resource_id));
			$this->view->operations=$rs_op;
						
			$this->view->gridShow=true;	
			$role_id=$this->getRequest()->getParam('role_id');
			$resource_id=$this->getRequest()->getParam('resource_id');
			$this->view->role_id=$role_id;
			$this->view->resource_id=$resource_id;
			
			
			Zend_Loader::loadClass('Permission');
			$permission=new Permission();
			$rs_permission=$permission->getList(array("role_id"=>$role_id,
													 "resource_id"=>$resource_id
															));
													
			
			$arr_permission=array();														
		    foreach((array)$rs_permission as $v){
		    	$arr_permission[$v['resource_row_id']]=$v;
		    }															
			$this->view->permission=$arr_permission;	
			$this->view->LANG=$LANG;													
		}else{
			$flag=true;
			//update db
			$formData=$this->getRequest()->getParams();			
			
			
			Zend_Loader::loadClass('Permission');
			$permission=new Permission();
			$formData=$permission->filterForm($formData);
			
			$permission->reset((int)($formData['role_id']),(int)($formData['resource_id']));
			
			$item=array("role_id"=>$formData['role_id'],'resource_id'=>$formData['resource_id']);
			
			Zend_Loader::loadClass("ResourceOp");
			$op=new ResourceOp();
			$rs_op=$op->getList(array("resource_id"=>$formData['resource_id']));
			
			foreach((array)$formData['resource_row_id'] as $row_id=>$v){
				
				if(!@$formData['resource_op_code'][$row_id] && $rs_op){
					//continue;
				}
				if($rs_op){
					$item['resource_op_code']=implode(",",(array)@$formData['resource_op_code'][$row_id]);
				}
				$item['resource_row_id']=$row_id;
				
				$flag =$flag && $permission->_insert($item);
			}
			$ret['success'] = $flag;
			$ret['msg'] = $flag?"save_ok":"save_fail";
			
			echo Baogg_Language::outputResult($ret);
					
			//echo '<pre>';echo Baogg_Db::debugDb(Zend_Registry::get('db')); print_r($this->getRequest()->getParams());
			$this->_helper->viewRenderer->setNoRender ();
			
		}
		
	}
	

}
